package com.cjb.cloudfabric.config;

import com.cjb.cloudfabric.entity.ContractValue;
import com.cjb.cloudfabric.entity.FabricUser;
import com.cjb.common.exception.ServerException;
import com.cjb.common.util.Common;
import org.hyperledger.fabric.gateway.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class ConnectGateWay
 * @Date 2023-10-07 下午11:31
 */
@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Service
public class FabricConfig {
    /**
     * 日志
     */
    private final static Logger log = LoggerFactory.getLogger(FabricConfig.class);
    /**
     * 钱包快捷路径
     */
    @Value("${fabric.basic-wallet}")
    private String walletPath;
    /**
     * org1连接文件
     */
    @Value("${fabric.config-path.org1Connect}")
    private String org1Connect;

    /**
     * 连接网关的api
     */
    @Autowired
    private ConnectGateWay connectGateWay;

    /**
     * 注册静态资源
     */
    static {
        System.setProperty("org.hyperledger.fabric.sdk.service_discovery.as_localhost", "true");
    }

    /**
     * 连接 --初始化生成admin
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE+1)
    void ConnectGateWay() {
        // enrolls the admin and registers the user
        try {
            connectGateWay.EnrollAdmin();
            FabricUser user = new FabricUser();
            user.setUserName("appUser");
            connectGateWay.RegisterUser(user);
        } catch (Exception e) {
            log.error("注册失败");
            log.error(String.valueOf(e));
            new ServerException("注册失败");
        }
//        try {
//            connect();
//        } catch (Exception e) {
//            log.error("连接失败");
//        }
    }

    /**
     * 连接网关
     */
    public Gateway connect() throws Exception {
        // Load a file system based wallet for managing identities.
        Path walletPath1 = Paths.get(walletPath);
        Wallet wallet = Wallets.newFileSystemWallet(walletPath1);
        // load a CCP
        Path networkConfigPath = Paths.get(org1Connect);

        Gateway.Builder builder = Gateway.createBuilder();
//        log.info("打印build {}", builder);
        builder.identity(wallet, "appUser").networkConfig(networkConfigPath).discovery(true);
        return builder.connect();
    }




    /*初始化链码 由于后续操作需要链码 所以我们尝试返回 contract 为后续使用提供*/
    public Contract initContract(ContractValue contractValue) throws Exception {
        log.info("---断点1---");
        Gateway gateway = connect();
        log.info("---断点2---");
        Network network;
        if (Common.isNotEmpty(contractValue)){
            network= contractValue.getChannel() == null ? gateway.getNetwork("mychannel")
                    : gateway.getNetwork(contractValue.getChannel());
            log.info("---断点3---");
            return contractValue.getContractName() == null ? network.getContract("basic")
                    : network.getContract(contractValue.getContractName());
        }else {
            log.info("---断点3---");
           network = gateway.getNetwork("mychannel");
            return network.getContract("basic");
        }


    }
}
